package com.zw.pdm.module.report.service;

import com.zw.pdm.constant.Constant;
import com.zw.pdm.entity.basic.Org;
import com.zw.pdm.entity.rep.Plan;
import com.zw.pdm.entity.rep.Sheet;
import com.zw.pdm.entity.sys.User;
import com.zw.pdm.module.basic.repository.OrgRepository;
import com.zw.pdm.module.report.mapper.SheetMapper;
import com.zw.pdm.module.report.repository.PlanRepository;
import com.zw.pdm.module.report.repository.SheetRepository;
import com.zw.pdm.module.system.service.LogService;
import com.zw.pdm.util.CommonUtils;
import com.zw.pdm.util.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.Date;


/**
 * @Description:
 *
 * @Author: China.sgl
 * @Date: 2019/12/6 08:42
 */
@Service
@SuppressWarnings("all")
public class ReportAddService {

    @Autowired
    private SheetRepository sheetRepository;
    @Autowired
    private SheetMapper sheetMapper;
    @Autowired
    private OrgRepository orgRepository;
    @Autowired
    private PlanRepository planRepository;
    @Autowired
    private LogService logService;

    private String msg = "";
    @Value("${user.upload.path}")
    private String uploadPath;

    /** 创建外购件 */
    @Transactional(rollbackFor = Exception.class)
    public int saveOut(Sheet sheet, String[] malDesc, Double[] num, String[] unit, String[] standard, String[] brand, String[] remark, String[] url) {
        sheet = genSheet(sheet);
        for (int i = 0; i < malDesc.length; i++) {
            Plan plan = new Plan();
            plan.setMalDesc(malDesc[i]);
            plan.setNum(num[i]);
            plan.setUnit(unit[i]);
            if (standard.length > 0) {
                plan.setStandard(standard[i]);
            }
            if (brand.length > 0) {
                plan.setBrand(brand[i]);
            }
            if (remark.length > 0) {
                plan.setRemark(remark[i]);
            }
            plan.setCreateTime(new Date());
            plan.setStatus(Constant.STATUS_NORMAL);
            plan.setSheetId(sheet.getId());
            plan.setAlreadyChange(0);
            plan = planRepository.save(plan);
            if (url.length > 0 && CommonUtils.isNotEmpty(url[i])) {
                StringBuffer dir = new StringBuffer();
                dir.append(uploadPath).append(sheet.getId()).append("/").append(plan.getId()).append("/");
                try {
                    org.apache.commons.io.FileUtils.moveToDirectory(new File(url[i]), new File(dir.toString()), true);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                StringBuffer srcPart = new StringBuffer();
                srcPart.append(uploadPath).append(ShiroUtils.getLoginName()).append("/temp/");
                StringBuffer targetPart = new StringBuffer();
                targetPart.append("/files/").append(sheet.getId()).append("/").append(plan.getId()).append("/");
                plan.setUrl(url[i].replace(srcPart.toString(), targetPart.toString()));
                plan.setUploadTime(new Date());
                planRepository.saveAndFlush(plan);
            }
        }
        logService.saveLog("外购件计划提报", "计划单ID：" + sheet.getId());
        return 1;
    }

    /** 创建外协件 */
    @Transactional(rollbackFor = Exception.class)
    public int saveAss(Sheet sheet, String[] malDesc, String[] diagram, Double[] num, String[] unit, String[] assistType, String[] remark, String[] url) {
        sheet = genSheet(sheet);
        for (int i = 0; i < malDesc.length; i++) {
            Plan plan = new Plan();
            plan.setMalDesc(malDesc[i]);
            plan.setNum(num[i]);
            plan.setUnit(unit[i]);
            if (diagram.length > 0) {
                plan.setDiagram(diagram[i]);
            }
            plan.setAssistType(assistType[i]);
            if (remark.length > 0) {
                plan.setRemark(remark[i]);
            }
            plan.setCreateTime(new Date());
            plan.setStatus(Constant.STATUS_NORMAL);
            plan.setSheetId(sheet.getId());
            plan.setAlreadyChange(0);
            plan = planRepository.save(plan);
            if (url.length > 0 && CommonUtils.isNotEmpty(url[i])) {
                StringBuffer dir = new StringBuffer();
                dir.append(uploadPath).append(sheet.getId()).append("/").append(plan.getId()).append("/");
                try {
                    org.apache.commons.io.FileUtils.moveToDirectory(new File(url[i]), new File(dir.toString()), true);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                StringBuffer srcPart = new StringBuffer();
                srcPart.append(uploadPath).append(ShiroUtils.getLoginName()).append("/temp/");
                StringBuffer targetPart = new StringBuffer();
                targetPart.append("/files/").append(sheet.getId()).append("/").append(plan.getId()).append("/");
                plan.setUrl(url[i].replace(srcPart.toString(), targetPart.toString()));
                plan.setUploadTime(new Date());
                planRepository.saveAndFlush(plan);
            }
        }
        logService.saveLog("外协件计划提报", "计划单ID：" + sheet.getId());
        return 1;
    }

    /** 创建原材料 */
    @Transactional(rollbackFor = Exception.class)
    public int saveMal(Sheet sheet, String[] malDesc, Double[] num, String[] unit, String[] standard, String[] quality, String[] useStore, String[] remark, String[] url) {
        sheet = genSheet(sheet);
        for (int i = 0; i < malDesc.length; i++) {
            // 保存计划
            Plan plan = new Plan();
            plan.setMalDesc(malDesc[i]);
            plan.setNum(num[i]);
            plan.setUnit(unit[i]);
            if (standard.length > 0) {
                plan.setStandard(standard[i]);
            }
            if (quality.length > 0) {
                plan.setQuality(quality[i]);
            }
            if (useStore.length > 0) {
                plan.setUseStore("是".equals(useStore[i]) ? 1 : 0);
            } else {
                plan.setUseStore(0);
            }
            if (remark.length > 0) {
                plan.setRemark(remark[i]);
            }
            plan.setCreateTime(new Date());
            plan.setStatus(Constant.STATUS_NORMAL);
            plan.setSheetId(sheet.getId());
            plan.setAlreadyChange(0);
            plan = planRepository.save(plan);
            // 如果包含上传文件，将文件移动到计划单+计划路径下，并保存到计划中
            if (url.length > 0 && CommonUtils.isNotEmpty(url[i])) {
                StringBuffer dir = new StringBuffer();
                dir.append(uploadPath).append(sheet.getId()).append("/").append(plan.getId()).append("/");
                try {
                    org.apache.commons.io.FileUtils.moveToDirectory(new File(url[i]), new File(dir.toString()), true);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                StringBuffer srcPart = new StringBuffer();
                srcPart.append(uploadPath).append(ShiroUtils.getLoginName()).append("/temp/");
                StringBuffer targetPart = new StringBuffer();
                targetPart.append("/files/").append(sheet.getId()).append("/").append(plan.getId()).append("/");
                plan.setUrl(url[i].replace(srcPart.toString(), targetPart.toString()));
                plan.setUploadTime(new Date());
                planRepository.saveAndFlush(plan);
            }
        }
        logService.saveLog("原材料计划提报", "计划单ID：" + sheet.getId());
        return 1;
    }

    /** 保存计划单 */
    private Sheet genSheet(Sheet sheet) {
        genBatchNo(sheet);
        User user = ShiroUtils.getUser();
        sheet.setPostUserId(user.getId());
        sheet.setPostName(user.getName());
        sheet.setDept(user.getDept());
        sheet.setDeptId(user.getDeptId());
        sheet.setBranchName(user.getBranchName());
        sheet.setCreateCode(ShiroUtils.getLoginName());
        sheet.setCreateId(user.getId());
        sheet.setCreateName(user.getName());
        sheet.setRawSplit(0);
        Org dept = orgRepository.getOne(ShiroUtils.getUser().getOrgId());
        if (dept != null) {
            sheet.setPostDept(dept.getName());
        }
        sheet.setCreateTime(new Date());
        sheet.setStatus(1);
        sheet.setSheetType(1);
        sheet.setMayChange(0);

        return sheetRepository.save(sheet);
    }

    /** 生成批次号 */
    private void genBatchNo(Sheet sheet) {
        Sheet st = sheetMapper.findFirstByBatchNo(sheet.getProCode());
        if (st == null) {
            sheet.setBatchNo(sheet.getProCode() + "N001");
        } else {
            int no = Integer.parseInt(CommonUtils.substring(st.getBatchNo(), st.getProCode().length() + 1));
            sheet.setBatchNo(sheet.getProCode() + "N" + CommonUtils.intToString(no+1, 3));
        }
    }

}
